<?php


namespace App\Http\Controllers\Api;

use App\Events\FileCreatedEvent;
use App\Http\Requests\ApiV2\UploadRequest;
use App\Services\Business\Models\Category;
use App\Services\Business\Models\File;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Services\Business\Interfaces\AttachServiceInterface;
use App\Services\Business\Services\AttachService;
use App\Services\Business\Interfaces\MyCategoryServiceInterface;
use App\Services\Business\Services\MyCategoryService;


class FileController extends BaseController
{
    /**
     * @var AttachService
     */
    protected $attachService;
    /**
     * @var MyCategoryService
     */
    protected $myCategoryService;

    public function __construct(
        MyCategoryServiceInterface $myCategoryService,
        AttachServiceInterface     $attachService
    )
    {
        $this->myCategoryService = $myCategoryService;
        $this->attachService = $attachService;

    }

    public function index(Request $request)
    {

        $excludeIds = $request->input('exclude_ids', []);
        $keywords = $request->input('keywords', '');
        $categoryId = $request->input('cid', 0);
        $size = $request->input('size', 10);
        $files = File::query()
            ->with(['user'])
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = Category::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->when($excludeIds, function ($query) use ($excludeIds) {
                $query->whereNotIn('id', $excludeIds);
            })
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->orderByDesc('created_at')
            ->paginate($size);
        return $this->successData(compact('files'));
    }


    public function upload(UploadRequest $request, File $file)
    {


        $data = $request->filldata();
        $file->fill($data)->save();

        return $this->successData(compact('file'));


    }

    /**
     * 文件详情
     * @param UploadRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function detail($id)
    {


        $file = File::query()->with(['user'])->where('id', $id)->firstOrFail()->toArray();
        return $this->successData(compact('file'));


    }

    public function list(Request $request)
    {


        $ids = $request->input('ids');
        if (!$ids) {
            $this->error(__('参数错误'));
        }
        $file = File::query()->whereIn('id', $ids)->get()->toArray();
        return $this->successData(compact('file'));


    }




    //文件已经保存到本地数据，不仅仅以删除oss的文件，还要删除本地数据的文件
    public function delete($id)
    {
        $file = File::query()->where('id', $id)->firstOrFail();

        // 删除附件
        Storage::disk('oss')->delete($file['path']);

        // 删除数据库记录
        $file->delete();

        return $this->success(__('文件删除成功'));
    }

    public function replace(UploadRequest $request, $id)
    {
        $data = $request->filldata();
        $file = File::query()->where('id', $id)->firstOrFail();
        //删除阿里云附件
        Storage::disk('oss')->delete($file['path']);
        $file->fill($data)->save();
        return $this->success(__('文件替换成功'));

    }

    public function updateTitle(Request $request, $id)
    {
        $title = $request->input('title');
        $file = File::query()->where('id', $id)->firstOrFail();
        $file->update(['title' => $title]);
        return $this->success();
    }

    public function storeResourceFiles(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($id) || empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->files()->attach($ids);
        return $this->success(__('添加文件成功'));


    }

    public function deleteResourceFiles(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($ids) || empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->files()->detach($ids);
        return $this->success(__('删除文件成功'));
    }


    public function download($id)
    {
        $file = File::query()->where('id', $id)->first();

         $this->downFile($file->url,$file->title);


    }


    public function downFile($url, $file_name)
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.android.package-archive;charset=UTF-8');
        header('Content-Disposition: attachment; filename=' . $file_name);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $buffer) {
            echo $buffer;
            return strlen($buffer);
        });
        curl_exec($ch);
        curl_close($ch);
    }
}
